<?php

namespace App\Http\Controllers\Chat\Web;



use App\Http\Controllers\Chat\BaseController;
use App\Models\Api\Chat;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\Request;
use WebSocket\Client;
use function env;
use function view;

class ChatController extends BaseController
{
    public function charRoom(Request $request)
    {
        $friendId = $request->input('uid');
        return view('users.chatRoom', compact('friendId'));
    }

    public function record(Request $request)
    {
        $uid = $request->input('uid');
        $fid = $request->input('fid');
        if(empty($uid) || empty($fid)) {
            return ApiResponseTrait::error('缺少参数');
        }

        $myRecord = Chat::whereUid($uid)->whereFid($fid)->get()->toArray();
        $friendRecord = Chat::whereUid($fid)->whereFid($uid)->get()->toArray();
        $all = array_merge($myRecord, $friendRecord);
        $new = array_column($all, 'created_at');
        array_multisort($new, SORT_ASC, $all);

        return ApiResponseTrait::success($all);
    }

    public function test(Request $request): \Illuminate\Http\JsonResponse
    {
        $token = $request->input('access_token');
        if(empty($token)) {
            return ApiResponseTrait::error('非法请求');
        }

        $client = new Client('ws://' . env('APP_DOMAIN') . ':9502?access_token=' . $token);
        $client->send('发送信息：' . __METHOD__);
        var_dump('接受信息： ', $client->receive());
        $client->close();
        return ApiResponseTrait::success();
    }
}
